<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽身体验课记录</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body>
    {% include 'show_ins_info.html' %}
    <div >
        <h2>鹿鹿泽健身体验课记录</h2>
        <div class="form-row"><h4 style="width:120px;">体验课上课时间</h4> <input type="datetime-local" id="dateInput" style="width:150px;" ></div>
        <div class="form-row"><h4 style="width:120px;">客户姓名/昵称 </h4><input type="text" id="cusNameInput" style="width:100px;" ></div>
        <div class="form-row">
                <h4 style="width:120px;">客户生日 </h4>
                <input type="date" id="cusBirthday">        
        
        </div>
        <div style="font-size: 9px;padding-left: 140px;">如客户只写到月，则日期填写1日，如：1993年3月→1993年3月1日</div>
        <div class="form-row">
            <h4 style="width:120px;">客户手机号</h4> <input type="text" id="mobilePhone" style="width:120px;" oninput="checkMobileValid()">
            <span id="mobileValidResult" style="display:inline; color:rgb(221, 126, 123)"></span>
        </div>
        
        <div id="insSelectBlock" class="form-row">
            <h4 style="width:120px;">上课教练 </h4>
            <select id="insSelect"></select>
        </div>
        
        <!-- <div id="" class="form-row">
            <h4 style="width:120px;">上课教练 </h4>
            <select id="">
                <option value="转介绍">转介绍</option>
                <option value="自行到店">自行到店</option>
                <option value="其他媒体">其他媒体</option>
            </select>
        </div> -->

        <div  class="form-row">
            <h4 style="width:120px;">客户来源</h4> 
            <select id="cusSource">
                <!-- <option value="小红书">小红书</option>
                <option value="转介绍">转介绍</option>
                <option value="自行到店">自行到店</option>
                <option value="其他媒体">其他媒体</option> -->
            </select>
        </div>

        <div class="form-row" style="margin-bottom: 20px;">
            <h4 style="width:120px;">体测发现</h4>  
            <textarea id='trialProblem' style="width:170px;height:100px;"></textarea>

        </div> 

        <div class="form-row">
            <h4 style="width:120px;">备注</h4>  
            <input type='text' id='comment' style="height:30px;">

        </div> 
        
    </div>
    <hr>
    <div id="dealProcessing" style="display:none;">正在处理，请稍候。</div>
    <button id="submit" onclick="submit()">提交</button>

    <script src="../static/js/moment.min.js"></script>
    <script src="../static/js/common.js"></script>
    <script> 
        let cus_list;
        let selectedName;
        let tmplt_info;
        let insName;
        let insId;
        let insRole;

        const allError={'dateError':0,'buyNumError':0};
        // 使用DOMContentLoaded事件监听，在页面加载完成后触发获取数据的操作
        document.addEventListener("DOMContentLoaded", function() {   
            // loginCheck();

            selectToday('dateInput','dateTime');
            selectToday('cusBirthday','date');

            fetch('/get_template_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                tmplt_info=data;    
                generateCusSrc(data);    
                  })
                .catch(error => console.error('Error:', error));

            

            fetch('/get_ins_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
                })
                .then(response => response.json())
                .then(insData => {
                    console.log(insData);
                    generateInsList(insData['ins_list'],'insSelect');
                    const insSel=document.getElementById('insSelect');
                    insSel.parentElement.classList.add('form-row');
                    
                 })
                .catch(error => console.error('Error:', error));

                insInfo=hideInsSelectBlockAndGetInsInfo('insSelectBlock');
                insId=insInfo.sessionInsId;
                insName=insInfo.sessionInsName;
                insRole=insInfo.sessionInsRole;

                ensureFormRowAfterAsyncOperation();

                // document.getElementById('trialProblem').value='1.test\n2.test2';
                // document.getElementById('trialProblem').value='1.颈部前引\n2.腰方肌过紧，胸椎活动度偏差\n3.肩峰撞击（肩关节活动度差）';

                // document.getElementById('insSelectBlock').classList.add('form-row');

                // console.log('dddd',document.getElementById('insSelectBlock').innerHTML)
                // console.log(document.getElementById('insSelectBlock').classList.contains('form-row'));

        });

        function generateCusSrc(data){
            const cusSrc=document.getElementById('cusSource');            
            const srcs=data['cus_source']
            srcs.forEach(src => {
                const opt=document.createElement('option');
                opt.value=src[0];
                opt.text=src[0]
                cusSrc.appendChild(opt);
            });
        }
        
        function ensureFormRowAfterAsyncOperation() {
            const insSelect = document.getElementById('insSelect');
            if (insSelect && insSelect.parentElement) {
                insSelect.parentElement.classList.add('form-row');
            }
        }

        function submit(){

            if(submitCheck()){
                const dateInput=document.getElementById('dateInput').value;
                const dateString=dateToString(dateInput,'date');
                const timeString=dateToString(dateInput,'time');
                const cusNameInput=document.getElementById('cusNameInput').value;
                const mobilePhone=document.getElementById('mobilePhone').value;
                // const insName=document.getElementById('insSelect').value;
                const cusBirthday=document.getElementById('cusBirthday').value;
                const cusSource=document.getElementById('cusSource').value;
                const trialProblem=document.getElementById('trialProblem').value;
                const comment=document.getElementById('comment').value;
                const dealProcessing=document.getElementById('dealProcessing')
                dealProcessing.style.display='block';

                if(insRole==='admin'){
                    insId=document.getElementById('insSelect').value;                    
                }else if(insRole==='ins'){
                    
                }

                
                
                data={
                    'dateString':dateString,
                    'timeString':timeString,
                    'cusNameInput':cusNameInput,
                    'cusBirthday':cusBirthday,
                    'mobilePhone':mobilePhone,
                    'insId':insId,
                    'insRole':insRole,
                    'cusSource':cusSource,
                    'trialProblem':trialProblem,
                    'comment':comment
                }
                fetch('/write_trial_rec',{
                    method:'POST',
                    headers:{
                        'Content-Type':'application/json'
                    },
                    body:JSON.stringify(data)                        
                })
                .then(response=>response.text())
                .then(writeResult=>{
                    console.log(writeResult);
                    alert(writeResult);
                    window.location.replace('./index');
                })
                .catch(error=>{
                    console.error('写入体验课错误：',e);
                });
            }
        }

        function submitCheck(){
            const cusNameInput=document.getElementById("cusNameInput").value;
            const mobilePhone=document.getElementById('mobilePhone').value;
            const mobilePattern = /^1[3-9]\d{9}$/;
            if(!cusNameInput || cusNameInput===''){
               return false; 
            }
            if(mobilePhone && !mobilePattern.test(mobilePhone)){
                return false;
            }
            
            return true;
        }

        function checkMobileValid(){
            const mobilePattern = /^1[3-9]\d{9}$/;
            const mobile=document.getElementById('mobilePhone').value;
            const mobileValidResult=document.getElementById('mobileValidResult');
            mobileValidResult.innerText='';
            if(mobile && mobile!==''){
                if(!mobilePattern.test(mobile)){
                    mobileValidResult.innerText='无效的手机号码'
                }

            }
        }


    </script>
</body>
</html>
